package util

import (
	models "gin-ebook/Models"
)

func SetMenuTree(data []models.Menu) (ret []models.Menu) {

	for index, ele := range data {
		node := &data[index]
		if hasChild(ele, data) {
			makeTree(data, node)
			ret = append(ret, *node)
		}
		continue
	}
	return
}

func makeTree(data []models.Menu, node *models.Menu) (first []models.Menu) {

	children := findChild(*node, data)
	for _, child := range children {
		node.Children = append(node.Children, child)
		if hasChild(child, data) {
			makeTree(data, &child)
		}
	}
	return
}

// 判断是否含有子菜单
func hasChild(v models.Menu, vs []models.Menu) (has bool) {
	has = false
	for _, v2 := range vs {
		if v.ID == v2.ParentID {
			return true
			break
		}
	}
	return
}

// 获取此节点的孩子菜单--指针类型
func findChild(v models.Menu, vs []models.Menu) (ret []models.Menu) {
	for _, v2 := range vs {
		if v.ID == v2.ParentID {
			ret = append(ret, v2)
		}
	}
	return
}
